# -*- coding: utf-8 -*-
"""
版权所有：J哥
微信号：wws_0904

关于python开发的网站：豆瓣 知乎(以前是python，现在是go)
https://www.acfun.cn/v/ac23857874
https://ali-safety-video.acfun.cn/mediacloud/acfun/acfun_video/hls/e16OPpnSxq6_sDsxLTKpfvNMdBJm_KuD3szOBRSWKQVsVUWmBtci-
Jfr37t5blk6.00000.ts?pkey=ABBJz6pwWGSCtosWok2Qmtlw9U0GyVF24hqKg8iP05UOgXxQ3xdZgwRpZPMO1zNLBAjk_vpHkL9a_yPi8Mt02kfBNd3WzP
ay8F9I9WTVfZAsS6a8yJXpGjupPzpKkiIw4I7cMquE41UN6hs1TtaCvDQ8RKSCDFXvU6CjOAL25vOHxF335EXMS55EGE_g0Ut7IECP72LsGFLGN2bU0BAzKX
30ZB4r1czwi_1RH8ihBRzqReXg7nLi2qvwjXCme3z9Akw&safety_id=AALToZH0bnvrjoT6IvSfsF75

详情页的网页源代码

"""

import requests
import re
import os
import zipfile  # 压缩文件的
from tqdm import tqdm  # 进度条显示
import random
import time

if not os.path.exists('A站视频'):
    os.makedirs('A站视频')


def vio_save():
    """下载视频片段"""
    url = 'https://www.acfun.cn/v/ac27904914'

    headers = {
        # 'Host': 'ali-safety-video.acfun.cn',
        # 'Origin': 'https://www.acfun.cn',
        # 'Referer': 'https://www.acfun.cn/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',
    }
    response = requests.get(url=url, headers=headers)
    # print(response)
    response.encoding = response.apparent_encoding
    res_txt = response.text
    # print(res_txt)

    # 视频片段地址  m3u8_url
    backupUrl = re.findall('backupUrl(.*?)\"]', res_txt, re.S)[0].replace('\\":[', '').replace('\\', '').replace('"',
                                                                                                                 '')
    # print(backupUrl)
    m3u8_resp = requests.get(url=backupUrl, headers=headers).text
    m3u8_resp = re.sub('#EXTM3U', '', m3u8_resp)
    m3u8_resp = re.sub('#EXT-X-VERSION:\d', '', m3u8_resp)
    m3u8_resp = re.sub('#EXT-X-TARGETDURATION:\d', '', m3u8_resp)
    m3u8_resp = re.sub('#EXT-X-MEDIA-SEQUENCE:\d', '', m3u8_resp)
    m3u8_resp = re.sub('#EXTINF:\d\.\d+,', '', m3u8_resp)
    m3u8_resp = re.sub('#EXT-X-ENDLIST', '', m3u8_resp)
    m3u8_resp = m3u8_resp.split()
    # print(m3u8_resp)
    i = 0
    for m3u8_urls in tqdm(m3u8_resp):  # 显示进度条
        m3u8_url = 'https://ali-safety-video.acfun.cn/mediacloud/acfun/acfun_video/hls/' + m3u8_urls
        # print(m3u8_url)
        # print('正在下载片段', i)
        resp = requests.get(url=m3u8_url, headers=headers)
        with open(f'A站视频\\片段{i}.ts', mode='wb') as f:
            f.write(resp.content)
        i += 1
    # print('下载成功')
    times = int(time.time())
    return times


# https://ali-safety-video.acfun.cn/mediacloud/acfun/acfun_video/hls/ +

def save(times):
    """可以手动合并，压缩成mp4文件格式"""
    int(random.random() * 10)

    path = 'A站视频\\'
    files = os.listdir(path)  # 读取文件
    print('开始合成')
    with zipfile.ZipFile(f'{path}合成效果{times}.mp4', mode='w') as z:
        for file in tqdm(files):
            path_file = path + file
            z.write(path_file)
            os.remove(path_file)
    print('合成成功')


time = vio_save()
save(time)
